import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { EventBusService } from 'src/app/common/event-bus.service';
import { HttpClient } from '@angular/common/http';
import { NzMessageService } from 'ng-zorro-antd/message';
import { res } from 'src/app/common/Interface';
@Component({
  selector: 'app-add-commodity',
  templateUrl: './add-commodity.component.html',
  styleUrls: ['./add-commodity.component.less'],
})
export class AddCommodityComponent implements OnInit {
  @Output('close') closeEvent = new EventEmitter();

  constructor(
    private evt: EventBusService,
    private http: HttpClient,
    private message: NzMessageService
  ) {}

  ngOnInit(): void {}
  forms = {
    commodity_name: '',
    unit: '个',
    price: null,
    in_num: null,
    in_price: null,
    payment: NaN,
    dealer: '',
  };
  close() {
    this.evt.bus.next('100%');
  }

  // '.' at the end or only '-' in the input box.
  onBlur(evt, key): void {
    this.updateValue(evt.target.value, key);
  }

  ngNumChange(n, obj = '') {
    const count_price = (parseFloat(n) || 0) * this.forms.in_price;
    this.forms.payment = count_price;
  }
  ngInPriceChange(n) {
    const price = Math.round(parseFloat(n) * 100) / 100;
    const count_price = (parseFloat(this.forms.in_num) || 0) * price;
    this.forms.payment = count_price;
  }

  updateValue(value: string, key): void {
    this.forms[key] = Math.round(parseFloat(value) * 100) / 100;
  }
  add() {
    this.http
      .post(`/commodity/add`, this.forms)
      .subscribe(({ code, data, msg }: res) => {
        this.message[code == 200 ? 'success' : 'error'](msg);
        if (code == 200) {
          this.evt.getListBus.next();
          this.close();
          this.forms = {
            commodity_name: '',
            unit: '个',
            price: null,
            in_num: null,
            in_price: null,
            payment: NaN,
            dealer: '',
          };
        }
      });
  }
}
